package com.gzsxy.esjy.service.core.sign.initialize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 这个上下文刷新事件是在 Spring 应用上下文(ApplicationContext)刷新之后发送。
 * @author zhangxiaolong
 * @date 2022/7/12 16:36
 */
@Component
@Slf4j
public class PdfConfigInitialize implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private PdfConfigCache pdfConfigCache;
    private final ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (null == pdfConfigCache.getConfigMap()) {
            try {
                String config = getResource(resourceLoader, "classpath:config/pdfConfig.json");
                if (StringUtils.isBlank(config)) {
                    config = getResource(resourceLoader, "file:config/pdfConfig.json");
                }
                List<PdfConfigDto> list = JSON.parseObject(config, new TypeReference<List<PdfConfigDto>>() {
                });

                Map<Integer, List<PdfConfigDto.MarkType>> collect = list.stream().collect(Collectors.toMap(PdfConfigDto::getPdfType, PdfConfigDto::getMarkTypeList));
                pdfConfigCache.setConfigMap(collect);

                //重庆提讯提解证初始化
                config = getResource(resourceLoader, "classpath:config/chongqingConfig.json");
                if (StringUtils.isBlank(config)) {
                    config = getResource(resourceLoader, "file:config/chongqingConfig.json");
                }
                list = JSON.parseObject(config, new TypeReference<List<PdfConfigDto>>() {
                });
                collect = list.stream().collect(Collectors.toMap(PdfConfigDto::getPdfType, PdfConfigDto::getMarkTypeList));
                pdfConfigCache.setChongqingMap(collect);

                //沈阳提讯小票初始化
                config = getResource(resourceLoader, "classpath:config/shenyangConfig.json");
                if (StringUtils.isBlank(config)) {
                    config = getResource(resourceLoader, "file:config/shenyangConfig.json");
                }
                list = JSON.parseObject(config, new TypeReference<List<PdfConfigDto>>() {
                });
                collect = list.stream().collect(Collectors.toMap(PdfConfigDto::getPdfType, PdfConfigDto::getMarkTypeList));
                pdfConfigCache.setShenyangMap(collect);

                config = getResource(resourceLoader, "classpath:config/pdfConfig-arraignCard.json");
                if (StringUtils.isBlank(config)) {
                    config = getResource(resourceLoader, "file:config/pdfConfig-arraignCard.json");
                }
                PdfConfigArraignCardDto cardDto = JSON.parseObject(config, PdfConfigArraignCardDto.class);
                pdfConfigCache.setArraignCardDto(cardDto);
            } catch (Exception e) {
                log.error("初始化PDF配置失败：{}", e.getMessage());
            }
        }
    }

    private String getResource(ResourcePatternResolver resourceLoader, String path) {
        Resource resource = resourceLoader.getResource(path);
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("加载PDF配置文件失败：{}:{}", path, e.getMessage());
            return null;
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}
